<template>
  <div class="app-container">
    <h2 style="text-align: center">发布新课程</h2>
    <el-steps
      :active="1"
      process-status="wait"
      align-center
      style="margin-bottom: 40px"
    >
      <el-step title="填写课程基本信息" />
      <el-step title="创建课程大纲" />
      <el-step title="最终发布" />
    </el-steps>

    <!-- 表单部分 -->
    <el-form label-width="120px">
      <el-form-item label="课程标题">
        <el-input
          v-model="courseInfoDto.title"
          placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"
        />
      </el-form-item>

      <!-- 所属分类：级联下拉列表 -->
      <!-- 一级分类 -->
      <el-form-item label="课程类别">
        <el-select
          v-model="courseInfoDto.subjectParentId"
          placeholder="一级分类"
          @change="subjectLevelOneChanged"
        >
          <el-option
            v-for="subject in subjectNestedList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"
          />
        </el-select>

        <!-- 二级分类 -->
        <el-select v-model="courseInfoDto.subjectId" placeholder="二级分类">
          <el-option
            v-for="subject in subSubjectList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"
          />
        </el-select>
      </el-form-item>

      <!-- 课程讲师 -->
      <el-form-item label="课程讲师">
        <el-select v-model="courseInfoDto.teacherId" placeholder="请选择">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="总课时">
        <el-input-number
          :min="0"
          v-model="courseInfoDto.lessonNum"
          controls-position="right"
          placeholder="请填写课程的总课时数"
        />
      </el-form-item>

      <!-- 课程简介-->
      <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfoDto.description" />
      </el-form-item>

      <!-- 课程封面-->
      <el-form-item label="课程封面">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :action="BASE_API + '/eduoss/fileoss/upfile'"
          class="avatar-uploader"
        >
          <img :src="courseInfoDto.cover" width="auto" height="150px" />
        </el-upload>
      </el-form-item>

      <el-form-item label="课程价格">
        <el-input-number
          :min="0"
          v-model="courseInfoDto.price"
          controls-position="right"
          placeholder="免费课程请设置为0元"
        />
        元
      </el-form-item>

      <el-form-item>
        <el-button
          :disabled="saveBtnDisabled"
          type="primary"
          @click="saveOrUpdate"
          >保存并下一步</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import course from "@/api/edu/course";
import teacher from "@/api/edu/teacher";
import subject from "@/api/subject/subject";
import Tinymce from "@/components/Tinymce";

export default {
  components: { Tinymce },
  data() {
    return {
      saveBtnDisabled: false, // 保存按钮是否禁用
      courseInfoDto: {
        // id: "",
        title: "",
        subjectId: "", //当前分类id
        subjectParentId: "", //课程分类父id
        teacherId: "",
        lessonNum: 0,
        description: "",
        cover:
          "https://xbli-edu.oss-cn-guangzhou.aliyuncs.com/2022/10/27/49645fbff885487caca2c90b2bb02ea8.png",
        price: 0,
      },
      teacherList: [], //讲师列表
      subjectNestedList: [], //一级分类列表
      subSubjectList: [], //二级分类列表
      BASE_API: process.env.BASE_API, // 接口API地址
      courseId: "", //课程id
    };
  },
  created() {
    //路由路径有id时，更新操作，反之添加操作
    if (this.$route.params && this.$route.params.id) {
      this.courseId = this.$route.params.id;
      // 根据id获取课程基本信息
      this.fetchCourseInfoById();
      //初始化所有讲师下拉列表
      this.getListTeacher();

      //根据一级分类初始化，课程类别回显
      this.getOneAndTowSubject();
    } else {
      //初始化所有讲师下拉列表
      this.getListTeacher();
      this.getOneSubject();
    }
  },
  watch: {
    //监听
    $route(to, from) {
      //路由变化方式，路由发生变化，方法就会执行
      this.init();
    },
  },
  methods: {
    //清空数据，恢复默认情况
    init() {
      //判断路径有id值,做修改
      if (this.$route.params && this.$route.params.id) {
        //从路径获取id值
      } else {
        //路径没有id值，做添加
        //清空表单
        this.courseInfoDto = {
          title: "",
          subjectId: "", //当前分类id
          subjectParentId: "", //课程分类父id
          teacherId: "",
          lessonNum: 0,
          description: "",
          cover:
            "https://xbli-edu.oss-cn-guangzhou.aliyuncs.com/2022/10/27/49645fbff885487caca2c90b2bb02ea8.png",
          price: 0,
        };
      }
    },
    //根据课程id获取课程基本信息
    fetchCourseInfoById() {
      course
        .getCourseById(this.courseId)
        .then((response) => {
          //保存回显的课程基本信息
          this.courseInfoDto = response.data.courseInfoFormDto;
        })
        .catch((response) => {
          this.$message({
            type: "error",
            message: response.message,
          });
        });
    },

    //上传封面成功
    handleAvatarSuccess(res, file) {
      console.log(res); // 上传响应
      console.log(URL.createObjectURL(file.raw)); // base64编码
      this.courseInfoDto.cover = res.data.url;
    },
    //上传封面之前
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 4;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 4MB!");
      }
      return isJPG && isLt2M;
    },
    //当改变一级分类时，触发该事件
    subjectLevelOneChanged(value) {
      //value就是一级分类的id值
      console.log(value);
      for (let i = 0; i < this.subjectNestedList.length; i++) {
        if (this.subjectNestedList[i].id === value) {
          this.subSubjectList = this.subjectNestedList[i].children;
          //把二级分类的值清空
          this.courseInfoDto.subjectId = "";
        }
      }
    },
    //查询所有的一级分类
    getOneSubject() {
      subject
        .getAllSubject()
        .then((response) => {
          this.subjectNestedList = response.data.list;
        })
        .catch((response) => {
          this.$message({
            type: "error",
            message: response.message,
          });
        });
    },
    //根据课程分类一级id查询,一级 二级分类
    getOneAndTowSubject() {
      subject
        .getAllSubject()
        .then((response) => {
          this.subjectNestedList = response.data.list;
          for (let i = 0; i < this.subjectNestedList.length; i++) {
            //判断回显的一级分类id 与 接口回显的一级分类id 一致
            if (
              this.courseInfoDto.subjectParentId == this.subjectNestedList[i].id
            ) {
              //保存二级分类类表
              this.subSubjectList = this.subjectNestedList[i].children;
            }
          }
        })
        .catch((response) => {
          this.$message({
            type: "error",
            message: response.message,
          });
        });
    },
    //查询所有的讲师
    getListTeacher() {
      teacher
        .getListTeacher()
        .then((response) => {
          this.teacherList = response.data.intems;
        })
        .catch((response) => {
          this.$message({
            type: "error",
            message: response.message,
          });
        });
    },
    saveOrUpdate() {
      //判断课程id为空
      if (!this.courseInfoDto.id) {
        //执行添加课程，基本信息操作
        course
          .addCourseInfo(this.courseInfoDto)
          .then((response) => {
            //提示信息
            this.$message({
              type: "success",
              message: "添加课程信息成功!",
            });
            //跳转到第二步，创建大纲
            this.$router.push({
              path: "/course/chapter/" + response.data.courseId,
            });
            console.log("next");
          })
          .catch((response) => {
            this.$message({
              type: "error",
              message: "保存失败",
            });
          });
      } else {
        //执行更新，课程基本信息操作
        course
          .updateCourseInfo(this.courseInfoDto)
          .then((response) => {
            //提示信息
            this.$message({
              type: "success",
              message: "修改课程信息成功!",
            });
            //跳转到第二步，创建大纲
            this.$router.push({
              path: "/course/chapter/" + this.courseId,
            });
            // console;
            console.log(this.courseId);
          })
          .catch((response) => {
            this.$message({
              type: "error",
              message: "更新失败",
            });
          });
      }
    },
  },
};
</script>
<style scoped>
.tinymce-container {
  line-height: 29px;
}
</style>